package com.yulintu.web;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * 文件上传
 * Created by caomin on 2017/10/12.
 */
@Controller
@RequestMapping("/dataCenter")
public class UploadController {


    @Value("${fileupload.path}")
    private String filePath;


    @PostMapping("/{taskId}/record/{tableName}/upload")
    public String upload(@RequestParam @PathVariable("taskId")String taskId, @RequestParam @PathVariable("tableName")String tableName, String parm, HttpServletRequest request) throws IOException {

        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
        Iterator<String> fileNames = multipartRequest.getFileNames();
        while (fileNames.hasNext()){//// TODO: 2017/10/15 获取不到文件
            String fileName = fileNames.next().toString();
            MultipartFile file = multipartRequest.getFile(fileName);
            file.transferTo(new File(filePath+File.separator+file.getOriginalFilename()));
        }
        if(resolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();

            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                    String path=filePath+File.separator+file.getOriginalFilename();
                    //上传
                    file.transferTo(new File(path));
                }
            }
        }
               // uploadUtils.save(parm,tableName);
        //更新附件记录
        //保存文件
        return "index";
    }



    @RequestMapping("/upload")
    public String toUpload(){
        return "index";
    }



}
